package com.zhouyu.mysql.core;

import com.zhouyu.mysql.dict.DictColumn;
import com.zhouyu.mysql.dict.DictTable;
import com.zhouyu.mysql.dict.SystemDict;
import net.sf.jsqlparser.expression.Expression;
import net.sf.jsqlparser.expression.LongValue;
import net.sf.jsqlparser.expression.NullValue;
import net.sf.jsqlparser.expression.StringValue;
import net.sf.jsqlparser.expression.operators.relational.EqualsTo;
import net.sf.jsqlparser.expression.operators.relational.ExpressionList;
import net.sf.jsqlparser.schema.Column;
import net.sf.jsqlparser.schema.Table;
import net.sf.jsqlparser.statement.insert.Insert;
import net.sf.jsqlparser.statement.select.FromItemVisitorAdapter;
import net.sf.jsqlparser.statement.select.PlainSelect;

import java.util.Optional;

/**
 * 大都督周瑜（我的微信: dadudu6789）
 */
public class DTupleUtil {

    public static DTuple convert(Insert insertStatement) {
        DTuple dTuple = new DTuple();

        String tableName = insertStatement.getTable().getName();
        ExpressionList<Column> columns = insertStatement.getColumns();
        ExpressionList<?> values = insertStatement.getValues().getExpressions();

        for (int i = 0; i < columns.size(); i++) {
            Column column = columns.get(i);
            Expression value = values.get(i);

            DictTable dictTable = SystemDict.getInstance().getNameTables().get(tableName);
            Optional<DictColumn> dictColumn = dictTable.getDictColumnList().stream().filter(c -> c.getName().equals(column.getColumnName())).findFirst();
            if (dictColumn.isPresent()) {
                DField dField = new DField();
                dField.setDictColumn(dictColumn.get());

                if (!(value instanceof NullValue)) {
                    if (dictColumn.get().isInt()) {
                        dField.setData(Integer.valueOf(value.toString()));
                    } else {
                        dField.setData(((StringValue) value).getValue());
                    }
                } else {
                    // 如果插入的是NULL，则用两个00表示
                    dField.setData("00");
                }

                dTuple.getFields().add(dField);
            } else {
                throw new RuntimeException(String.format("%s字段不存在", column.getColumnName()));
            }
        }

        return dTuple;
    }
}
